import jwt from 'express-jwt'
import path from 'path'
import helmet from 'helmet'
import bodyParser from 'body-parser'
import morgan from 'morgan'
import fileStreamRotator from 'file-stream-rotator'

module.exports = app => {
  const { logDirectory, isDev, env } = app.config.commonConfig
  const { secret } = app.config.auth[env]

  app.use(helmet())
  app.use(bodyParser.json())
  app.use(
    /^\/api\/\w+(\/\w+)?/,
    jwt({
      secret
    }).unless({
      path: ['/api/common/token', '/api/user/login', '/api/user/regisiter']
    })
  )
  app.use(
    morgan(`${isDev ? 'dev' : 'common'}`, {
      stream: isDev
        ? null
        : fileStreamRotator.getStream({
            date_format: 'YYYYMMDD',
            filename: path.join(logDirectory, 'log-%DATE%.log'),
            frequency: 'daily',
            verbose: false
          })
    })
  )
}
